﻿#region Creditos

/* Autor: Edilberto Sánchez Forero	*/
/* Email: esanchezfo@gmail.com		*/
/* Licencia: Propietario			*/
/* País: Colombia, Bogotá			*/

#endregion


#region Librerias

using System.ComponentModel;
using System.Linq;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using ESF.General;
using ESF.Web;
using ESF.SSO.Web.Tools.Modules;
using ESF.General.MVP;
using ESF.SSO.Core.Entities;
using ESF.Web.Pages;
using ESF.SSO.Web.Tools.Presenter;
using System.Collections.Generic;
using ESF.General.Entity;
using System;

#endregion


namespace ESF.SSO.Web.Tools.ServerControls
{
	[AspNetHostingPermission(SecurityAction.Demand,
        Level = AspNetHostingPermissionLevel.Minimal),
    AspNetHostingPermission(SecurityAction.InheritanceDemand, 
        Level = AspNetHostingPermissionLevel.Minimal),
	ToolboxData ("<{0}:LoginView runat=\"server\"></{0}:LoginView>")]
	public class LoginView : BaseServerControl<LoginViewPresenter>, IPostBackEventHandler, INamingContainer, ILoginViewViewer
	{
		#region Propiedades

		public string LinkTarget
		{
			set
			{
				ViewState["LinkTarget"] = value;
			}
			get
			{
				if (ViewState["LinkTarget"] == null)
				{
					return AuthenticationModule.LinkTarget;
				}

				return ViewState["LinkTarget"] as string;
			}
		}

		#endregion


		#region Delegados
		
		public delegate void ChangeApplicationCodeEvent ();
		
		public event ChangeApplicationCodeEvent OnChangeApplicationCode;
		
		#endregion
	
	
		#region Miembros
		
		private LinkButton lnkCloseSession;
		
		private HyperLink lnkEditUser;
		
		private Label lblUserEnterpriseName;
		private Label lblUserExtraEnterpriseName;

		#endregion
				
		
		#region Inicializacion
		
		protected override void CreateChildControls()
		{
			lnkCloseSession = new LinkButton ();
			lnkCloseSession.CausesValidation = false;
			lnkCloseSession.ID = "lnkCloseSession";
			lnkCloseSession.Text = resLoginView.lnkCloseSession_Text;
			lnkCloseSession.ToolTip = resLoginView.lnkCloseSession_ToolTip;
			lnkCloseSession.CssClass = "CloseSession item";
			lnkCloseSession.Click += lnkCloseSession_Click;
			
			
			lnkEditUser = new HyperLink ();
			lnkEditUser.ID = "lnkEditUser";
			lnkEditUser.Text = "Editar sus Datos";
			lnkEditUser.ToolTip = "De click para editar la información de su cuenta";
			lnkEditUser.CssClass = "EditUser item";
			lnkEditUser.Target = LinkTarget;
			lnkEditUser.NavigateUrl = AuthenticationModule.SSOAdminMainURL + "/User/EditUser.aspx";


			lblUserEnterpriseName = new Label ();
			lblUserEnterpriseName.CssClass = "lblUserEnterpriseName";
			lblUserEnterpriseName.ID = "lblUserEnterpriseName";
			
			if (AuthenticationModule.SignedInUser.Enterprise != null)
			{
				lblUserEnterpriseName.Text = AuthenticationModule.SignedInUser.Enterprise.Name;
			}
			else
			{
				lblUserEnterpriseName.Visible = false;
			}


			lblUserExtraEnterpriseName = new Label ();
			lblUserExtraEnterpriseName.CssClass = "lblUserExtraEnterpriseName";
			lblUserExtraEnterpriseName.ID = "lblUserExtraEnterpriseName";

			if (AuthenticationModule.SignedInUser.extEnt != null)
			{
				lblUserExtraEnterpriseName.Text = AuthenticationModule.SignedInUser.extEnt.Name;
			}
			else
			{
				lblUserExtraEnterpriseName.Visible = false;
			}


			Controls.Add (lnkCloseSession);
			Controls.Add (lblUserEnterpriseName);
			Controls.Add (lblUserExtraEnterpriseName);
		}

		private void lnkCloseSession_Click(object sender, System.EventArgs e)
		{
			Page.Trace.Write (string.Format ("LoginView Close Session Start for {0} {1}", frmUserAlias, frmIsAuthenticated));

			_Presenter = new LoginViewPresenter (this);

			_Presenter.CloseSession();

			Page.Trace.Write(string.Format("LoginView Close Session End for {0} {1}", frmUserAlias, frmIsAuthenticated));
		}
		
		#endregion


		#region PreRender

		protected override void OnPreRender(System.EventArgs e)
		{
			base.OnPreRender(e);

			_Presenter = new LoginViewPresenter(this);

			
			lnkCloseSession.Visible = frmIsAuthenticated;
		}

		#endregion
		
		
		#region Eventos
		
		public void lnkChangeApplication_Click (string pApplicationCode, string pApplicationName)
		{
			frmApplicationCode = pApplicationCode;
			frmApplicationName = pApplicationName;
			
			if (OnChangeApplicationCode != null)
			{
				OnChangeApplicationCode ();
			}
		}
		
		#endregion
		
		
		#region Render
		
		protected override void Render (HtmlTextWriter pWriter)
		{
			List<UserMenuItem> appList;

			PostBackOptions postOpt;

			UserMenuItem currentApp;


			postOpt = new PostBackOptions(this);

			appList = AuthenticationModule.UserApplicationList;

			HttpContext.Current.Trace.Write ("LoginView Render Start");

			if (DataHelper.IsEmpty (appList))
			{
				JS.AddWarning (Page, "No le ha sido configurado el acceso a las aplicaciones, consulte con su administrador");
				return;
			}

			appList.RemoveAll(apl => apl.Code == "ESF.SSO.Client");

			if (!frmIsAuthenticated && appList.Count == 1) { return; }

				pWriter.AddAttribute(HtmlTextWriterAttribute.Class, (string.IsNullOrEmpty(CssClass) ? "loginView" : CssClass));
			pWriter.RenderBeginTag (HtmlTextWriterTag.Div);

				if (appList.Count > 1)
				{
					currentApp = appList.FirstOrDefault (a => a.Code == frmApplicationCode);

					if (currentApp == null)
					{
						currentApp = appList.First ();

						lnkChangeApplication_Click (currentApp.Code, currentApp.Name);
					}

					pWriter.RenderBeginTag(HtmlTextWriterTag.Ul);

							pWriter.AddAttribute(HtmlTextWriterAttribute.Class, currentApp.Code.Replace(".", "_")); 
						pWriter.RenderBeginTag(HtmlTextWriterTag.Li);

								pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "level_1"); 
								pWriter.AddAttribute(HtmlTextWriterAttribute.Title, currentApp.Description);
									
								if (appList.Count > 1)
								{
									pWriter.AddAttribute(HtmlTextWriterAttribute.Onclick, "$('#" + ClientID + "_apps').toggle();"); 
								}

							pWriter.RenderBeginTag (HtmlTextWriterTag.A);

								pWriter.RenderBeginTag(HtmlTextWriterTag.Div);
									pWriter.Write(currentApp.Name);
								pWriter.RenderEndTag();

								if (appList.Count > 1)
								{
										pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "arrow");
										pWriter.AddAttribute(HtmlTextWriterAttribute.Src, Page.ClientScript.GetWebResourceUrl(GetType(), "ESF.SSO.Web.Tools.ServerControls.Images.Icons.BulletArrowDown_10x10.gif"));
									pWriter.RenderBeginTag(HtmlTextWriterTag.Img);
									pWriter.RenderEndTag(); 
								}

							pWriter.RenderEndTag();	

						pWriter.RenderEndTag();
							
									
						#region Menus de las otras Aplicaciones

						if (appList.Count > 1)
						{
								pWriter.AddAttribute(HtmlTextWriterAttribute.Title, "De click en el nombre de la aplicación para cambiar el menú, identifiquelas por el color de su banda izquierda"); 
								pWriter.AddAttribute (HtmlTextWriterAttribute.Id, ClientID + "_apps");
								pWriter.AddAttribute (HtmlTextWriterAttribute.Style, "display:none;");
							pWriter.RenderBeginTag(HtmlTextWriterTag.Ul);
						
								postOpt.Argument = string.Empty;
								postOpt.PerformValidation = false;

								foreach (UserMenuItem app in appList.Where(a => a.Code != currentApp.Code))
								{
									postOpt.Argument = "ChangeApplicationCode|" + app.Code + "|" + app.Name;

										pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "level_2"); 
									pWriter.RenderBeginTag(HtmlTextWriterTag.Li);

											pWriter.AddAttribute(HtmlTextWriterAttribute.Class, app.Code.Replace(".", "_")); 
											pWriter.AddAttribute(HtmlTextWriterAttribute.Title, app.Description);
											pWriter.AddAttribute (HtmlTextWriterAttribute.Onclick, Page.ClientScript.GetPostBackEventReference(postOpt) + ";");
										pWriter.RenderBeginTag (HtmlTextWriterTag.A);

												pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "flag");
											pWriter.RenderBeginTag(HtmlTextWriterTag.Div);
											pWriter.RenderEndTag();

											pWriter.RenderBeginTag(HtmlTextWriterTag.Span);
												pWriter.Write(app.Name);
											pWriter.RenderEndTag(); 
										pWriter.RenderEndTag();

									pWriter.RenderEndTag();
								}

								#endregion

							pWriter.RenderEndTag();
						}

					pWriter.RenderEndTag();
				}
					
				if (AuthenticationModule.IsAuthenticated)
				{
						pWriter.AddAttribute(HtmlTextWriterAttribute.Id, "esfsso_userOptions");
					pWriter.RenderBeginTag(HtmlTextWriterTag.Div);

						pWriter.RenderBeginTag(HtmlTextWriterTag.Ul);

								pWriter.AddAttribute (HtmlTextWriterAttribute.Class, "level_1");
							pWriter.RenderBeginTag(HtmlTextWriterTag.Li);
								
									pWriter.AddAttribute (HtmlTextWriterAttribute.Onclick, "$('#" + ClientID + "_useroptions').toggle();"); 
									pWriter.AddAttribute (HtmlTextWriterAttribute.Class, "UserAlias");
								pWriter.RenderBeginTag (HtmlTextWriterTag.A);
									pWriter.RenderBeginTag(HtmlTextWriterTag.Div);
										
												pWriter.AddAttribute (HtmlTextWriterAttribute.Class, "fullName");
											pWriter.RenderBeginTag (HtmlTextWriterTag.Div);
												pWriter.Write (AuthenticationModule.SignedInUser.calFullName);
											pWriter.RenderEndTag();

											lblUserEnterpriseName.RenderControl (pWriter);
											lblUserExtraEnterpriseName.RenderControl (pWriter);

									pWriter.RenderEndTag();
										pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "arrow");
										pWriter.AddAttribute(HtmlTextWriterAttribute.Src, Page.ClientScript.GetWebResourceUrl(GetType(), "ESF.SSO.Web.Tools.ServerControls.Images.Icons.BulletArrowDown_10x10.gif"));
									pWriter.RenderBeginTag(HtmlTextWriterTag.Img);
									pWriter.RenderEndTag();
								pWriter.RenderEndTag(); 

							pWriter.RenderEndTag();
							
								pWriter.AddAttribute (HtmlTextWriterAttribute.Id, ClientID + "_useroptions");
							pWriter.RenderBeginTag(HtmlTextWriterTag.Ul);
								lnkCloseSession.RenderControl (pWriter);									
								lnkEditUser.RenderControl (pWriter);
							pWriter.RenderEndTag ();
							
						pWriter.RenderEndTag ();

					pWriter.RenderEndTag();
				}
						
			pWriter.RenderEndTag ();
			
			
			HttpContext.Current.Trace.Write ("LoginView Render End");
		}
		
		#endregion
		
		
		#region Miembros de IPostBackEventHandler

		public void RaisePostBackEvent (string pEventArgument)
		{
			string [] parts;
			
		
			parts = pEventArgument.Split ('|');
		
			pEventArgument = parts [0];
		
			switch (pEventArgument)
			{
				case "ChangeApplicationCode": lnkChangeApplication_Click (parts [1], parts [2]); break;
			}
		}

		#endregion


		#region Miembros de ILoginViewer

		public string UserSessionID
		{
			get { return AuthenticationModule.SessionID; }
		}
		
		
		public User SignedInUser
		{
			get { return AuthenticationModule.SignedInUser; }
		}
		
		
		public void ClearSession ()
		{
			AuthenticationModule.ClearSession ();

			JS.AddWarning (Page, "Su sesión ha sido cerrada.\nSerá dirigido a la página principal");

			JS.AddGoTop (Page, RequestHelper.AppendVarValueToHTTPURL (ReadConfig.MainURL));
		}

		#endregion
	}
}
